<!DOCTYPE html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/common/includes.jsp"%>
<html>
<head>
<title>多PI入库编辑</title>
<!-- import css and js -->
<%@ include file="/common/metaInput.jsp"%>
<script src="${ctx}/js/jsp/comm.js" type="text/javascript"></script>
<script type="text/javascript" src="${ctx}/js/My97DatePicker/WdatePicker.js"></script>
<script type="text/javascript" src="${ctx}/js/jsp/yd/logic/ItemStateData.js"></script>
<script src="${ctx}/js/jsp/date.js" type="text/javascript"></script>
<script type="text/javascript">
	var basic_Url = "${ctx}/logic/batchIn";
	var addressGrid;
	var print=false; //是否打印的状态标识 true 为打印  在 点击提交的时候进行打印
	var obj;
	$(function() {
		obj={'zd008MaterialAllMoney':$("#zd008MaterialAllMoney").val(),'zd003WhName':$("#zd003WhName").val(),'zd006MakerName':'${userName}','zd009Remark':$("#zd009Remark").val(),'zd004InDate': $("#zd004InDate").val(),'zd007SupplierName':$("#zd007SupplierName").val(),'zd002InNumber':$("#zd002InNumber").val(),'zd001Code':$("#zd001Code").val()};
		$("#inputForm").validate({
			onsubmit : true,
			/*执行ajaxsubmit  */
			submitHandler : function(editform) {

				try {
					url = basic_Url + "/save.do";
					var api = frameElement.api;
					var W = api.opener;
					//obj 主表对象 data 行记录 print 是不是为提交状态(提交才打印) where 什么的打印 区别 例如 其他入库，其他出库等
					var data=getNeedData(addressGrid.getData());
					getReturnMessageThree(url, "inputForm", W.searchAP,"",obj,data,print,"batchIn");
				} catch (e) {
					alert(e);
				}
			}
		});
		var column1 = [           
				    { display: 'id', name: 'id',type: 'string',hide:true},
				    { display: '物料id', name: 'zd002MaterId',width:1,hide:true},//使用selecturl时必须设置该属性
				    { display: '<font color="gray">物料编码</font>', name: 'zd002MaterCode', width: 100},
		            { display: '<font color="gray">名称</font>', name: 'zd002MaterName',width: 80},
		            { display: '<font color="gray">型号<font color="red">*</font></font>', name: 'zd002MaterModel' ,width: 100,editor : {type :'text'}},
		            { display: '<font color="gray">尺寸<font color="red">*</font></font>', name: 'zd002MaterSpec' ,width: 100,editor : {type :'text'}},
		            { display: '<font color="gray">颜色<font color="red">*</font></font>', name: 'zd002MaterColor' ,width: 80,editor : {type :'text'}},
		            { display: '<font color="gray">材质<font color="red">*</font></font>', name: 'zd002MaterQuanlity' ,width: 80,editor : {type :'text'}},
		            { display: '<font color="gray">基本单位</font>', name: 'zd006Uint',width: 50,editor : {type :'text'}},
		            { display: '<font color="gray">PI单号</font>', name: 'zd005PiCode',width: 100,editor : {type :'text',onChanged: changed}},
		            { display: '客户ID', name: 'zd004CustomerId',width: 1,hide:true},
		            { display: '客户Code', name: 'zd004CustomerCode',width: 1,hide:true},
		            { display: '客户名称', name: 'zd004CustomerName',width: 80},
		            { display: '入库数量<font color="red">*</font>', name: 'zd003InQuantity',editor : {type :'float'},width: 80,render:function(item){
                   		var price = item.zd007Price;//单价
                   		var zdnum = item.zd003InQuantity;//数量
                   		if((!isNaN(price)&&price!=null&&price!=undefined) && (!isNaN(zdnum)&&zdnum!=''&&zdnum!=null&&zdnum!=undefined)){
                   			item.zd008AllMoney = (parseFloat(price)*parseFloat(zdnum)).toFixed(4);
                   			getSumMoney();
                   		}
                	 	return (1*zdnum).toFixed(4);
                 	}},
                 	
	                { display: '单价<font color="red">*</font>', name: 'zd007Price' ,editor : {type :'float'},width: 80,render:function(item){
	                	var price = item.zd007Price;//单价
                   		var zdnum = item.zd003InQuantity;//数量
                   		if((!isNaN(price)&&price!=''&&price!=null&&price!=undefined) && (!isNaN(zdnum)&&zdnum!=''&&zdnum!=null&&zdnum!=undefined)){
                   			item.zd008AllMoney = (parseFloat(price)*parseFloat(zdnum)).toFixed(4);
                   			getSumMoney();
                   		}
                	 	return (1*price).toFixed(4);
                 	}},
                    { display: '反审数量<font color="red">*</font>', name: 'zd003BackInQuantity',width: 80,render:function(item){
		            	if(isNaN(item.zd003BackInQuantity)){
		            		return '0.00';
		            	}else{
		            		return item.zd003BackInQuantity;
		            	}
		            }},
		            { display: '系列', name: 'zd008AllMoney',width: 80,hide:true},
	                { display: '总金额<font color="red">*</font>', name: 'zd008AllMoney',width: 80},
	                { display: '描述', name: 'zd009Describtion' ,width: 120,editor : {type :'text'}}
	                ];
		
	var column2 = [
				    { display: 'id', name: 'id',type: 'string',hide:true},
				    { display: '物料id', name: 'zd002MaterId',width:1,hide:true},//使用selecturl时必须设置该属性
				    { display: '<font color="gray">物料编码</font>', name: 'zd002MaterCode', width: 100},
		            { display: '<font color="gray">名称</font>', name: 'zd002MaterName',width: 80},
		            { display: '<font color="gray">型号<font color="red">*</font></font>', name: 'zd002MaterModel' ,width: 100,editor : {type :'text'}},
		            { display: '<font color="gray">尺寸<font color="red">*</font></font>', name: 'zd002MaterSpec' ,width: 100,editor : {type :'text'}},
		            { display: '<font color="gray">颜色<font color="red">*</font></font>', name: 'zd002MaterColor' ,width: 80,editor : {type :'text'}},
		            { display: '<font color="gray">材质<font color="red">*</font></font>', name: 'zd002MaterQuanlity' ,width: 80,editor : {type :'text'}},
		            { display: '<font color="gray">基本单位</font>', name: 'zd006Uint',width: 50},
		            { display: '<font color="gray">PI单号</font>', name: 'zd005PiCode',width: 100},
		            { display: '客户名称', name: 'zd004CustomerName',width: 100},
		            { display: '入库数量<font color="red">*</font>', name: 'zd003InQuantity',width: 80},
	                { display: '单价<font color="red">*</font>', name: 'zd007Price' ,width: 80},
                    { display: '反审数量<font color="red">*</font>', name: 'zd003BackInQuantity',width: 80,render:function(item){
		            	if(isNaN(item.zd003BackInQuantity)){
		            		return '0.00';
		            	}else{
		            		return item.zd003BackInQuantity;
		            	}
		            }},
	                { display: '总金额<font color="red">*</font>', name: 'zd008AllMoney',width: 80},
	                { display: '描述', name: 'zd009Describtion' ,width: 120}
		          ];
	 var column3 = null;
		               if ("${bi.zd010Stauts}" == ""||//新增
		            		   "${bi.zd010Stauts}"=="BATCHIN_SAVE"||//保存
		            		   		"${bi.zd010Stauts}"=="BATCHIN_BACK"){//退回
		               	column3 = column1;
		               }else {
		            	   column3 = column2;
		               }
		               addressGrid = $("#dataGrid1").ligerGrid({
		           		 columns: column3,
		           	                    enabledEdit : true,
		           	                    usePager: true,
		           	      				width : '99%',
		           	      				pageSize:1000,
		           	      				pageSizeOptions:[1000],
		           	      				parms:[{ name : 'id' , value : '${bi.id}'}],
		    	      		        	url : basic_Url+"/griditems.do",
		           	      				rownumbers : false,
		           	      				checkbox : true,
		           	                    height : '90%',
		           		toolbar : {
		           			items : [ {
		           				text : '新增',
		           				disable : true,
		           				click : function() {
		           					if ($("#zd010Stauts").val()==""||$("#zd010Stauts").val()=="BATCHIN_SAVE"){
		        						if($("#zd003WhCode").val()==''){
		        							$.dialog.alert("请先选择入库仓库");
		        							return false;
		        						}else{
			           						getDG().dialog({
			           				    		title:'选择材料',
			           				    		width : 800,
			           							height : 400,
			           							content: 'url:' + sys_context+'/public/windowalert/itemmanager.do',//
			           				    		lock : true,
			           				    		max : true,
			           				    		min : true,
			           				    		ok: function(){
			           				    			var rows = this.content.getSelected();
			           								if (rows != null) {
			           									for (var i = 0; i < rows.length;i++){
			           										var row = rows[i];
			           										addressGrid.addRow2({
			           											zd002MaterId : row.id,
			           											zd002MaterCode : row.zd001Code,
			           											zd002MaterName : row.zd002Name,
			           											zd002MaterModel : row.zd004Model,
			           											zd002MaterSpec : row.zd026Size,
			           											zd002MaterColor : row.zd033Color,
			           											zd002MaterQuanlity : row.zd034Quality,
			           											zd006Uint : row.basicStapleUnitDO.zd002Name,
			           											zd007Price :0.00,
			           											zd003InQuantity:0.00,
			           											zd008AllMoney:'0.000'
			           										});
			           									}
			           								}
			           				    			this.content.Close();
			           				        		return false;
			           				    	    },
			           				    	    cancelVal: '关闭',
			           				    	    cancel: true 
			           				    	}).zindex();
		        						}
		           					}
		           				},
		           				icon: 'add'
		           			}, 
		           		 <c:if test="${bi.zd010Stauts == null ||bi.zd010Stauts =='BATCHIN_SAVE'}">
		           			{line : true},
		           			{text : '复制物料',click : addWindow,icon: 'add'},
		           			{line : true}, {
		           				text : '删除',
		           				click : function() {
		           					addressGrid.deleteSelectedRow();
		           				},
		           				img : '${ctx}/js/ligerUI/skins/icons/delete.gif'
		           			}
		           			</c:if>
		           			]
		           		}});
	});
	$(function(){
		var zd010Stauts=$("#zd010Stauts").val();
		if(zd010Stauts==''||zd010Stauts=='BATCHIN_BACK'){//新增 或者是退会的时候
			$("#tr1").hide();
			$("#tr").hide();
			$("#save1").hide();
			$("#save2").hide();
			$("#save3").hide();
			$("#print1").hide();
			$("#print2").hide();
		}else if(zd010Stauts=="BATCHIN_SAVE"){//保存 待提交
			$("#save2").hide();
			$("#save3").hide();
			if($("#zd006MakerName").val()!="${user.name}"){
				$("#save1").hide();
				$("input[type!='hidden']").attr("disabled",true);//禁用SELECT标签
				$("select").attr("disabled",true);//禁用SELECT标签
				$("textarea").attr("disabled",true);//禁用TEXTAREA标签
	           }  
		}else if (zd010Stauts == "BATCHIN_SUBMIT"){ // 提交 待审核
			$("#save").hide();
			$("#save1").hide();
			$("input[type!='hidden']").attr("disabled","disabled");//禁用SELECT标签
			$("select").attr("disabled","disabled");//禁用SELECT标签
			$("textarea").attr("disabled","disabled");//禁用TEXTAREA标签
		}else if ( zd010Stauts == "BATCHIN_END"){//审核完成
			$("#save1").hide();
			$("#save2").hide();
			$("#save3").hide();
			$("#save").hide();
			$("input[type!='hidden']").attr("disabled","disabled");//禁用SELECT标签
			$("select").attr("disabled","disabled");//禁用SELECT标签
			$("textarea").attr("disabled","disabled");//禁用TEXTAREA标签
		}
	});
	function submitForm(param) {
	 	$("#zd010Stauts").val(param);
	 	var dataInfo=$("#dataGrid1").ligerGetGridManager().getData();
	 	for(var i=0;i<dataInfo.length;i++){
	 		dataInfo[i].zd010Order=i+"";
	 		if(dataInfo[i].zd005PiCode==""||dataInfo[i].zd005PiCode==null){
	 			$.dialog.alert("数据错误,您的第"+(i+1)+"行PICode不能为空");
	 			return false;
				break;
	 		}
	 	}
	 	$("#addressInfos").val(JSON.stringify(dataInfo));
		var data = $("#dataGrid1").ligerGetGridManager().getData();
		var br=false;
		var arr= new Array();
		for(var i=0;i<data.length;i++){
			var key=data[i].zd002MaterName+"_"+data[i].zd002MaterCode+"_"+data[i].zd002MaterModel+"_"+data[i].zd002MaterSpec+"_"+data[i].zd002MaterColor+"_"+data[i].zd002MaterQuanlity+"_"+data[i].zd005PiCode;
			arr[i]=key;
			for(var j = 0 ;j<i;j++){
				if(arr[j]==key){
					$.dialog.alert("数据错误,您的第"+(i+1)+"和第"+(j+1)+"条的物品是同一物品,请确认后提交");
					br=true;
					break;
				}			
			}
			if(br){
				return false;
				break;
			}
		}
		if(data.length==0){
			$.dialog.alert("请增加物料信息");
	   	 	return false;
		}
		var ba=true;
		if(data !=null){
			for (var i = 0;i < data.length;i++){
				var row = data[i];
				
				if (undefined == row.zd006Uint|| null == row.zd006Uint||row.zd006Unit=="") {
					$.dialog.alert("第" + (i+1) + "行的单位没有选择");
					ba = false;
					return false;
				}
				if(undefined == row.zd003InQuantity
						|| isNaN(row.zd003InQuantity)
						|| row.zd003InQuantity <= 0){
		           	 $.dialog.alert("您第"+(i+1)+"行的“入库数量”不合法");
		           	 ba=false;
		           	 return false;
		        }
			}
			
		}
		//设置ajax全局同步
		jQuery.ajaxSettings.async = false;
		if(ba){
			$("#submitFlag").val(param);
			//判断是否为提交 在提交的时候打印
			if(param=='BATCHIN_SUBMIT'){
				print=true;
			}
			$("#inputForm").submit();
		}
	}
	//取得总金额
	function getSumMoney(){
		var zdTheSumMoney = '0';
		var cRows = addressGrid.getData();
		for(var i=0; i<cRows.length; i++){
			var cRow = cRows[i];
			var sumMoney = cRow.zd008AllMoney;
			if(sumMoney==null||sumMoney==''||sumMoney==undefined||isNaN(sumMoney)){
				sumMoney = '0';
			}
			zdTheSumMoney = parseFloat(zdTheSumMoney)+parseFloat(sumMoney);
		}
		$("#zd008MaterialAllMoney").val(zdTheSumMoney.toFixed(4));
	}
	
	function close(){
		var api = frameElement.api;
		var W = api.opener;
		CloseDialog();
		W.searchAP();
	}
	//出库仓库
	function  SotrageinfoWindow() {
		getDG().dialog(
				{
					title : '选择仓库',
					width : 650,
					height : 350,
					content : 'url:' + sys_context + '/public/windowalert/sotrageinfo.do?roleQuery=y',    
					lock : true,
					max : true,
					min : true,
					ok : function() {
						var rows = this.content.getSelected();
						if(rows==null){
							$.dialog.alert("请选择数据");
							return;
						}
						else{
							if(rows.length>1){
								$.dialog.alert('只能选择一行数据!');
								return;
							}else{
								$(rows).each(function() {
									$("#zd003WhId").val(this.id);
									$("#zd003WhCode").val(this.zd002Code);
									$("#zd003WhName").val(this.zd003Name);
							  });
							}
						}
						this.content.Close();
						return false;
					},
					cancelVal : '关闭',
					cancel : true
				}).zindex();
	}
	

	
	
	//客户列表
	function CompanyWindow() {
		getDG().dialog(
				{
					title : '选择供应商',
					width : 650,
					height : 350,
					content : 'url:' + sys_context + '/public/windowalert/company.do?zdType='+" ",    
					lock : true,
					max : true,
					min : true,
					ok : function() {
						var rows = this.content.getSelected();
						if(rows==null){
							$.dialog.alert("请选择数据");
							return;
						}
						else{
							if(rows.length>1){
								$.dialog.alert('只能选择一行数据!');
								return;
							}else{
								$(rows).each(function() {
									$("#zd007SupplierCode").val(this.zd001Code);
									$("#zd007SupplierId").val(this.id);
									$("#zd007SupplierName").val(this.zd003ZhName);
							  });
							}
						}
						this.content.Close();
						return false;
					},
					cancelVal : '关闭',
					cancel : true
				}).zindex();
	}
	function PrintView(type){
		if(type==1){
			window.parent.parent.loadPrint(obj,getNeedData(addressGrid.getData()),"batchIn",false);
		}else{
			window.parent.parent.loadPrint(obj,getNeedData(addressGrid.getData()),"batchIn",true);
		}
	}
	function getNeedData(data){
		var arr= new Array();
		for(var i=0;i<data.length;i++){
			if(!isNaN(data[i].zd003BackInQuantity)){
				data[i].zd003InQuantity=parseFloat(data[i].zd003InQuantity)-parseFloat(data[i].zd003BackInQuantity);
			}
			
			if(parseFloat(data[i].zd003InQuantity)!=0){
				arr.push(data[i]);
			}
		}
		return arr;
	}
	//复制物料
		function addWindow(){
			var cRows = addressGrid.getCheckedRows();
			if(cRows.length==0){
				$.dialog.alert("请选择要复制的物料行！");
				return false;
			}
			var manager = $("#dataGrid1").ligerGetGridManager();
			for(var i=0; i<cRows.length;i++){
				manager.addRow({
					zd002MaterId : cRows[i].zd002MaterId,
					zd002MaterCode : cRows[i].zd002MaterCode,
					zd002MaterName : cRows[i].zd002MaterName,
					zd002MaterModel : cRows[i].zd002MaterModel,
					zd002MaterSpec : cRows[i].zd002MaterSpec,
					zd002MaterColor : cRows[i].zd002MaterColor,
					zd002MaterQuanlity : cRows[i].zd002MaterQuanlity,
					zd006Uint : cRows[i].zd006Uint,
					zd007Price :0.00,
					zd003InQuantity:0.00,
					zd008AllMoney:'0.000'
				});
			};
		}
	//输入pi后自动获取里面的内容
function changed(e){
	var data=addressGrid.getRow($(e).parent()[0]);
	if(data.zd005PiCode==null||data.zd005PiCode==""){
		$.dialog.alert("PI编号不能为空");
	}else{
		$.ajax({
			url:"${ctx}/logic/sales/getCustomer.do",
			global: false,
			type:"POST",
			dataType:"json",
			data:({"picode":data.zd005PiCode }),
			 success: function(msg){
				 if(msg.msg=="success"){
		    		  addressGrid.updateCell("zd004CustomerId",msg.customerId,data);
		    		  addressGrid.updateCell("zd004CustomerName",msg.customerName,data);
		    		  addressGrid.updateCell("zd004CustomerCode",msg.customerCode,data);
					}else{
						$.dialog.alert("此pi系统没有录入");
					}  
		   }
		});
	}
}

</script>

</head>

<body>

	<form id="inputForm" action="" method="post">
		<input type="hidden" id="id" name="id" value="${bi.id}" />
		<input type="hidden" id="addressInfos" name="addressInfos"/>
		<input type="hidden" id="dataItem" name="dataItem"/>
		<input type="hidden" id="bizVersion" name="bizVersion" value="${bi.bizVersion}"/>
		<input type="hidden" id="zd010Stauts" name="zd010Stauts" value="${bi.zd010Stauts}"/>
		<!-- 用于标识提交按钮 -->
		<input type="hidden" id="submitFlag" value="" />
		<div class="pageContent">
			<div class="panel">
				<table class="TableBlock">
					<tr >
					 	<td nowrap id="tr1">单号:</td>
						<td id='tr'><input type="text" id="zd001Code" name="zd001Code" readonly="readonly"  value="${bi.zd001Code}" /></td>
						 <td nowrap >送货单号:</td>
						<td ><input   type="text" id="zd002InNumber" name="zd002InNumber"  value="${bi.zd002InNumber}" /></td>
					 </tr>
					<tr>
					 	<td nowrap>入库仓库:</td>
						<td>
						      <input type="hidden" id="zd003WhCode" name="zd003WhCode" value="${bi.zd003WhCode}"/>
   		                      <input type="text" id="zd003WhName" name="zd003WhName" readonly="readonly" value="${bi.zd003WhName}"/>
	   		            	  <input type="hidden" style="width:200px;" id="zd003WhId"  name="zd003WhId" value="${bi.zd003WhId}" />
   		        			  <input type="button" value="..." onclick="SotrageinfoWindow();" />
						</td>
						
					 	<td nowrap>入库时间:</td>
						<td><input id="zd004InDate" name="zd004InDate" class="inp_width_98p required" onclick="WdatePicker({dateFmt:'yyyy-MM-dd'})" value="<fmt:formatDate value="${bi.zd004InDate}" pattern="yyyy-MM-dd" type="both" />" /></td>
						 	 <c:if test="${bi.zd004InDate == null}">
									<script>
										var date = new Date();
										$("#zd004InDate").val(date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate());
									</script>
							 </c:if>
					</tr>
					 <tr>
   		            	<td nowrap="nowrap">供应商编号:</td>
   		           		<td><input type="text" style="width:200px;" id="zd007SupplierCode" name="zd007SupplierCode" value="${bi.zd007SupplierCode}" readonly="readonly" class=" required"></input>
   		           		<input type="button" value="..." onclick="CompanyWindow();" />
   		           		</td>
   		           		<td nowrap="nowrap">供应商名称:</td>
   		           		<td>
   		                 <input type="text" style="width:200px;" id="zd007SupplierName" readonly="readonly" name="zd007SupplierName" value="${bi.zd007SupplierName}" class="required"></input>
   		                 <input  type="hidden" name="zd007SupplierId"  id="zd007SupplierId" value="${bi.zd007SupplierId}"/>
   		                 </td>
   		           		
   		           </tr>
					<tr>
						<td nowrap>制单人:</td>
						<td> 
							<input type="text" id="zd006MakerName" name="zd006MakerName" class="inp_width_98p" value="${user.name}" readonly="readonly"/>
							<c:if test="${bi.zd006MakerName != null}">
								<script>
									$("#zd006MakerName").val("${bi.zd006MakerName}");
								</script>
							</c:if>
						</td>
						<td nowrap>总金额:</td>
						<td>
							<input type="text" id="zd008MaterialAllMoney" name="zd008MaterialAllMoney" readonly="readonly"  value="${bi.zd008MaterialAllMoney}" />
						</td>
					</tr>

					<tr>
						<td nowrap>备注:</td>
						<td><input class="inp_width_98p"  type="text" id="zd009Remark" name="zd009Remark"  value="${bi.zd009Remark}" /></td>
					</tr>
					<tr>
						<td colspan="4" style="margin-bottom: 10px;"><div
								id="dataGrid1"></div></td>
					</tr>
				</table>
			</div>
			<div class="formBar">
				<ul>
					 <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save" onclick="submitForm('BATCHIN_SAVE')">保存</button></div></div></li>
					 <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save1" onclick="submitForm('BATCHIN_SUBMIT')">提交</button></div></div></li>
		        <webres:displaycontroller elementId="LOGIC_BATCHIN_SP" description="分PI录入入库单审批">
			       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save2" onclick="submitForm('BATCHIN_END')">审核通过</button></div></div></li>
			    </webres:displaycontroller>
			    <webres:displaycontroller elementId="LOGIC_BATCHIN_SP" description="分PI录入驳回">
			       <li><div class="buttonActive"><div class="buttonContent"><button type="button" id="save3" onclick="submitForm('BATCHIN_BACK')">驳回</button></div></div></li>
			    </webres:displaycontroller>
		       	<li id=print1><div class="buttonActive"><div class="buttonContent"><button type="button" id="forPrint" onclick="PrintView(1);">打印预览</button></div></div></li>
		      	<li id=print2><div class="buttonActive"><div class="buttonContent"><button type="button" id="forPrint" onclick="PrintView(2);">打印</button></div></div></li>
		       <li><div class="button"><div class="buttonContent"><button type="button" class="print" onclick="CloseDialog()">关闭</button></div></div></li>
				</ul>
			</div>
		</div>
	</form>
</body>
</html>
